<script setup>
import { View } from '@element-plus/icons-vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import { classesListService, studentListService } from '@/api/student.js'
import {
  getStudentAverageGradeService,
  getStudentGradesAllService,
  getStudentTotalGradeService,
  gradeAddService,
  updateGradeService,
  deleteGradeService
} from "@/api/grades";
import { courseAllService } from '@/api/course.js'
import { teachersListService } from '@/api/teacher'

const classes = ref([])

const classId = ref('')

const courses = ref([])

const id = ref('')

const students = ref([
  {
    id: '',
    name: '',
    classId: '',
    grade: '',
    totalGrade: 0,
    averageGrade: 0,
  }
])

const grades = ref([
  {
    courseId: '',
    studentId: '',
    grade: '',
  }
])

const studentId = ref('')

const pageNum = ref(1)

const total = ref(0)

const pageSize = ref(5)

const onSizeChange = (size) => {
  pageSize.value = size
  studentList()
}
const onCurrentChange = (num) => {
  pageNum.value = num
  studentList()
}

let pageSizes = [5, 10, 15];

const classesList = async () => {
  let result = await classesListService();
  classes.value = result.data;
}

const gradeList = async () => {
  try {
    let result = await getStudentGradesAllService();
    grades.value = result.data;
  } catch (error) {
    console.log('Error fetching data:', error)
  }
}

const courseList = async () => {
  try {
    let result = await courseAllService();
    courses.value = result.data;
  } catch (error) {
    console.log('Error fetching data:', error)
  }
}

const studentList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    classId: classId.value ? classId.value : null,
    studentId: studentId.value ? studentId.value : null,
    id: id.value ? id.value : null
  }
  let result = await studentListService(params);
  total.value = result.data.total;
  students.value = result.data.items;
  for (let i = 0; i < students.value.length; i++) {
    let student = students.value[i];
    for (let j = 0; j < classes.value.length; j++) {
      if (student.classId == classes.value[j].id) {
        student.className = classes.value[j].name;
      }
    }
    let total = await getStudentTotalGradeService(student.id);
    let average = await getStudentAverageGradeService(student.id);
    student.totalGrade = total.data;
    student.averageGrade = await average.data;
  }
}

classesList();

gradeList();

studentList();

courseList();

const dialogVisible = ref(false)

const visibleDrawer = ref(false)

const gradeModel = ref({
  studentId: '',
  courseId: '',
  grade: '',
})

const title = ref('')

const clearData = () => {
  gradeModel.value = {
    studentId: '',
    courseId: '',
    grade: '',
    courseTeacher: ''
  }
}

// 添加学生成绩
const addGrade = async () => {
  await gradeAddService(gradeModel.value);
  ElMessage.success('添加成功');
  dialogVisible.value = false;
  await studentList();
}

const studentGrades = ref([]);

const showGrades = async (row) => {
  studentGrades.value = [];
  title.value = '查看学生[' + row.name + ']的成绩';
  for (let i = 0; i < grades.value.length; i++) {
    if (grades.value[i].studentId == row.id) {
      studentGrades.value[i] = grades.value[i];
    }
    for (let i = 0; i < studentGrades.value.length; i++) {
      let studentGrade = studentGrades.value[i];
      for (let j = 0; j < courses.value.length; j++) {
        if (studentGrade == undefined) continue;
        if (studentGrade.courseId == courses.value[j].id) {
          studentGrade.courseName = courses.value[j].name;
          let result = await teachersListService();
          for (let n = 0; n < result.data.length; n++) {
            if (courses.value[j].teacherId == result.data[n].id) {
              studentGrade.courseTeacher = result.data[n].name;
            }
          }
        }
      }
    }
  }
  visibleDrawer.value = true;
}

const getGradeModel = async (row) =>{
  gradeModel.value = {
    studentId: row.studentId,
    courseId: row.courseId,
    grade: row.grade,
  }
}

const editGrade = async () =>{
  await updateGradeService(gradeModel.value);
  ElMessage.success('添加成功');
  dialogVisible.value = false;
  await studentList();
}

const deleteGrade = (row) =>{
  ElMessageBox.confirm('此操作将永久删除该成绩， 是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteGradeService(row);
    ElMessage.success('删除成功');
    studentList();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>成绩列表</span>
        <div class="extra">
          <el-button type="primary" @click="dialogVisible = true; clearData(); title = '添加学生成绩'">添加学生成绩
          </el-button>
        </div>
      </div>
    </template>
    <el-form inline>
      <el-form-item label="学生班级：">
        <el-select v-model="classId" placeholder="请选择">
          <el-option v-for="c in classes" :key="c.id" :label="c.name" :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生ID：">
        <el-input v-model="id" placeholder="请输入学生ID"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="studentList()">搜索</el-button>
        <el-button @click="classId = ''; id = ''; studentList()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="students" style="width: 100%">
      <el-table-column label="学生姓名" prop="name" width="150"></el-table-column>
      <el-table-column label="学号" prop="id"></el-table-column>
      <el-table-column label="班级" prop="className"></el-table-column>
      <el-table-column label="总成绩" prop="totalGrade"></el-table-column>
      <el-table-column label="平均成绩" prop="averageGrade"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="View" circle plain type="primary" @click="showGrades(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="pageSizes" :total="total"
      background layout="jumper, total, sizes, prev, pager, next" style="margin-top: 20px; justify-content: flex-end"
      @size-change="onSizeChange" @current-change="onCurrentChange" />

    <!-- 添加成绩弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="gradeModel" label-width="100px" style="padding-right: 30px">
        <el-form-item v-if="title==='添加学生成绩'" label="学生" prop="studentId">
          <el-select v-model="gradeModel.studentId" placeholder="请选择">
            <el-option v-for="s in students" :key="s.id" :label="s.name" :value="s.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title==='添加学生成绩'" label="课程" prop="courseId">
          <el-select v-model="gradeModel.courseId" placeholder="请选择">
            <el-option v-for="c in courses" :key="c.id" :label="c.name" :value="c.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title==='修改学生成绩'" label="学生" prop="studentId">
          <el-select v-model="gradeModel.studentId" placeholder="请选择" :disabled="true">
            <el-option v-for="s in students" :key="s.id" :label="s.name" :value="s.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title==='修改学生成绩'" label="课程" prop="courseId">
          <el-select v-model="gradeModel.courseId" placeholder="请选择" :disabled="true">
            <el-option v-for="c in courses" :key="c.id" :label="c.name" :value="c.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="grade">
          <el-input v-model="gradeModel.grade"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" v-if="title === '添加学生成绩'" @click="addGrade()"> 确认 </el-button>
          <el-button v-if="title === '修改学生成绩'" type="primary" @click="editGrade()"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!--单个学生成绩情况抽屉-->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="80%">
      <el-table :data="studentGrades" style="width: 100%">
        <el-table-column label="课程Id" prop="courseId"></el-table-column>
        <el-table-column label="课程名称" prop="courseName"></el-table-column>
        <el-table-column label="任课教师" prop="courseTeacher"></el-table-column>
        <el-table-column label="成绩" prop="grade"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="dialogVisible=true;getGradeModel(row);title = '修改学生成绩'">编辑</el-button>
            <el-button type="danger" @click="deleteGrade(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>